/******************************************************************************
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
if(typeof Cc == "undefined")
  var Cc = Components.classes;
if(typeof Ci == "undefined")
  var Ci = Components.interfaces;
if(typeof Cu == "undefined")
  var Cu = Components.utils;
if(typeof cfxc == "undefined")
	var cfxc = {};
		
	cfxc.h = {
		prefs: Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch),
		
		_disabled: false,
		
		get _mainWindow() {
			delete this._mainWindow;
			return this._mainWindow = document.getElementById("main-window");
		},
		
		get _statusbarMenuItem() {
			delete this._statusbarMenuItem;
			return this._statusbarMenuItem = document.getElementById("cfx-statbardisable-menuitem");
		},
		
		get _tabbarMenuitem() {
			delete this._tabbarMenuitem;
			return this._tabbarMenuitem = document.getElementById("cfx-tabbar-menuitem");
		},

		get _uiMenuitem() {
			delete this._uiMenuitem;
			return this._uiMenuitem = document.getElementById("cfx-uidisable-menuitem");
		},
		
		get _navbar() {
			delete this._navbar;
			return this._navbar = document.getElementById("nav-bar");
		},
		
		get _cfxcStrings() {
			delete this._cfxcStrings;
			return this._cfxcStrings = document.getElementById("cfxcStrings");
		},
		
		get _statusbar() {
			delete this._statusbar;
			return this._statusbar = document.getElementById("status-bar");
		},
		
		get _statusbarDisplay() {
			delete this._statusbarDisplay;
			return this._statusbarDisplay = document.getElementById("statusbar-display");
		},
		
		get _findBar() {
			delete this._findBar;
			return this._findBar = document.getElementById("FindToolbar");
		},
		
		get _browserContainer() {
			delete this._browserContainer;
			return this._browserContainer = document.getElementById("browser");
		},
	
		onLoad: function() {
			this.setTheme();
			if(this.getPref("Disabled") === false) {
				this.setFindbar();
				this.setFullscreen();
				cfxc.observer.register();
				this.setTabMode();
				if(this.getPref("DisableUI") === true) {
					this._mainWindow.setAttribute("cfx-uiDisabled", "true");
				} else {
					this.setIdentity();
				}
				if(this.getPref("FirstRun") === true) {
					this.setPref("FirstRun", false);
					this.installButtons();
				}
				this.customizeDone();
			}
		},
		
		getPref: function(prefName) {
			return this.prefs.getBoolPref("extensions.cfxh." + prefName);
		},
		
		getCharPref: function(prefName) {
			return this.prefs.getCharPref("extensions.cfxh." + prefName);
		},
		
		setPref: function(prefName, val) {
			this.prefs.setBoolPref("extensions.cfxh." + prefName, val);
		},
		
		setCharPref: function(prefName, val) {
			this.prefs.setCharPref("extensions.cfxh." + prefName, val);
		},
		
		setTheme: function() {
			let currentTheme = this.prefs.getCharPref("general.skins.selectedSkin");
			switch(currentTheme) {
				case "cfxe":
					this._mainWindow.setAttribute("cfx-theme", "cfxe");
					if(this.getPref("Disabled") === true) {
						this.setPref("Disabled", false);
					}
					break;
				case "cfxeblade":
					this._mainWindow.setAttribute("cfx-theme", "cfxeblade");
					if(this.getPref("Disabled") === true) {
						this.setPref("Disabled", false);
					}
					break;
				case "cfxec":
					this._mainWindow.setAttribute("cfx-theme", "cfxec");
					if(this.getPref("Disabled") === true) {
						this.setPref("Disabled", false);
					}
					break;
				default:
					this.setPref("Disabled", true);
					this._disabled = true;
					break;
			}
			this.resetTabWidth();
		},
		
		resetTabWidth: function() {
			if(!this._disabled) {
				if(this.prefs.getIntPref("browser.tabs.tabMaxWidth") != 195) {
					this.prefs.setIntPref("browser.tabs.tabMaxWidth", 195);
					this.restartApp();
				}
			} else if(this._disabled) {
				if(this.prefs.getIntPref("browser.tabs.tabMaxWidth") == 195) {
					this.prefs.setIntPref("browser.tabs.tabMaxWidth", 250);
					this.restartApp();
				}
			}
		},
		
		setFullscreen: function() {
			this._mainWindow.setAttribute("cfx-fullscreen", "false");
			this._navbar.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
		},
		
		setFindbar: function() {
			let mainWindow = document.getElementById("main-window");
			mainWindow.setAttribute("cfx-findbar", "true");
			this._findBar.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
			mainWindow.insertBefore(this._findBar, this._browserContainer);
		},
		
		setTabMode: function() {
			let tabMode = this.getCharPref("Tabs");
			switch(tabMode) {
				case "top":
					this._mainWindow.setAttribute("cfx-tabs", "top");
					break;
				case "default":
					this._mainWindow.setAttribute("cfx-tabs", "default");
					break;
				case "basic":
					this._mainWindow.setAttribute("cfx-tabs", "basic");
					break;
				default:
					break;
			}
		},

		setIdentity: function() {
			this._identityLabel.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
			this._starButton.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
			let cfxStarbutton = document.getElementById("cfx-star-button"); 
			let onClick = window.PlacesStarButton.onClick.toString();
			onClick = onClick.replace('PlacesCommandHook.bookmarkCurrentPage(this._starred);', 'if (gURLBar.getAttribute("pageproxystate") != "invalid") { PlacesCommandHook.bookmarkCurrentPage(this._starred); }');
			let bookmarkPage = window.PlacesCommandHook.bookmarkPage.toString();
			bookmarkPage = bookmarkPage.replace(/"star-button"/g, '"' + cfxStarbutton.id + '"');
			let bmarkString = "window.PlacesCommandHook.bookmarkPage = " + bookmarkPage;
			let identityButton = document.getElementById("cfx-identity-button");
			this.IdentityHandler = window.gIdentityHandler;
			delete this.IdentityHandler._identityBox;
			this.IdentityHandler._identityBox = identityButton;
		/*
			let identityBox = window.document.getElementById("identity-box");    
			let starButton = window.document.getElementById("star-button");
			starButton.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
    
			let cfxStarbutton = identityBox.cloneNode(false);
			cfxStarbutton.tooltipText = starButton.tooltipText;
			cfxStarbutton.id = "cfx-star-button";
			cfxStarbutton.setAttribute("onclick", starButton.getAttribute("onclick"));
			cfxStarbutton.removeAttribute("onkeypress");
    
			let onClick = window.PlacesStarButton.onClick.toString();
			onClick = onClick.replace('PlacesCommandHook.bookmarkCurrentPage(this._starred);', 'if (gURLBar.getAttribute("pageproxystate") != "invalid") { PlacesCommandHook.bookmarkCurrentPage(this._starred); }');
    
			let bookmarkPage = window.PlacesCommandHook.bookmarkPage.toString();
			bookmarkPage = bookmarkPage.replace(/"star-button"/g, '"' + cfxStarbutton.id + '"');

			cfxStarbutton.appendChild(identityBox.firstChild.cloneNode(false));
			cfxStarbutton.firstChild.setAttribute("pack", "center");
			identityBox.parentNode.appendChild(cfxStarbutton);
         
			let identityButton = starButton.cloneNode(true);
			identityButton.id = "cfx-identity-button";
			identityButton.setAttribute("onclick", identityBox.getAttribute("onclick"));
			identityButton.setAttribute("tooltiptext", identityBox.tooltipText);
    
			this.IdentityHandler = window.gIdentityHandler;
			delete this.IdentityHandler._identityBox;
			this.IdentityHandler._identityBox = identityButton;
    
			let identityLabel = document.getElementById("identity-icon-label");
			identityLabel.addEventListener("DOMAttrModified", this.onDOMAttrModified, false);
    
			let cfxIdentityLabel = identityLabel.cloneNode(true);
			cfxIdentityLabel.id = "cfx-identity-icon-label";
			let urlbarIcons = document.getElementById("urlbar-icons");
			urlbarIcons.insertBefore(cfxIdentityLabel, starButton);
			urlbarIcons.insertBefore(identityButton, cfxIdentityLabel);
		*/
		},

		installButtons: function() {
			let newSet = this._navbar.currentSet + ",cfx-control-button";
			this._navbar.setAttribute("currentset", newSet);
			this._navbar.currentSet = newSet;
			document.persist(this._navbar, "currentset");
			newSet = this._navbar.currentSet + ",cfx-tools-button";
			this._navbar.setAttribute("currentset", newSet);
			this._navbar.currentSet = newSet;
			document.persist(this._navbar, "currentset");
		},
		
		onDOMAttrModified: function(e) {
			switch(e.attrName) {
				case "hidden":
					if(e.target.id == "FindToolbar") {
						var mainWindow = document.getElementById("main-window");
						if(!e.newValue) {
							mainWindow.setAttribute("cfx-findbar", "false");
						} else if(e.newValue == "true") {
							mainWindow.setAttribute("cfx-findbar", e.newValue);
						}
					}
					break;
				case "moz-collapsed":
					if(e.target.id == "nav-bar") {
						var mainWindow = document.getElementById("main-window");
						mainWindow.setAttribute("cfx-fullscreen", e.newValue);
					}
					break;
				case "value":
					if(e.target.id == "identity-icon-label") {
						var cfxIdentityLabel = document.getElementById("cfx-identity-icon-label");
						if(cfxIdentityLabel) {
							cfxIdentityLabel.value = e.newValue;
						}
					}
					break;
				case "tooltiptext":
					if(e.target.id == "star-button") {
						var cfxStarButton = document.getElementById("cfx-star-button");
						if(cfxStarButton) {
							var urlBar = document.getElementById("urlbar");
							if(urlBar.getAttribute("pageproxystate") == "invalid") {
								cfxStarButton.tooltipText = "";
							} else {
								cfxStarButton.tooltipText = e.target.tooltipText;
							}
						}
					} else if(e.target.id == "identity-box") {
						var identityButton = document.getElementById("cfx-identity-button");
						if(identityButton) {
							identityButton.tooltipText = e.target.tooltipText;
						}
					}
					break;
				case "starred":
					if(e.target.id == "star-button") {
						var cfxStarButton = document.getElementById("cfx-star-button");
						if(cfxStarButton) {
							if(e.attrChange == 3) {
								cfxStarButton.removeAttribute("starred");
							} else {
								cfxStarButton.setAttribute("starred", e.newValue);
							}
						}
					}
					break;
				case "pageproxystate":
					if(e.target.id == "urlbar") {
						var cfxStarButton = window.document.getElementById("cfx-star-button");
						var starButton = window.document.getElementById("star-button");
						if(cfxStarButton) {
							if(e.newValue == "invalid") {
								cfxStarButton.tooltipText = "";
							} else {
								cfxStarButton.tooltipText = starButton.tooltipText;
							}
						}
					}
					break;
				default:
					break;
			}
		},
		
		customizeDone: function() {
			try {
				BrowserToolboxCustomizeDone(true);
			} catch(e) {}
			if(this.getPref("DisableUI") === false) {
				let identityButton = document.getElementById("cfx-identity-button");
				identityButton && (this.IdentityHandler._identityBox = identityButton);
			}
		},
		
		restartApp: function() {
			if (!window.canQuitApplication()) {
				return;
			}
			let appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].getService(Ci.nsIAppStartup);
			appStartup.quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit);
		},
		
		vacuum: function() {
			Cc["@mozilla.org/browser/nav-history-service;1"].getService(Ci.nsPIPlacesDatabase).DBConnection.executeSimpleSQL("VACUUM");
			let alertsService = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
			alertsService.showAlertNotification("chrome://cfxhelper/skin/vacuum.png", this._cfxcStrings.getString("vac"), this._cfxcStrings.getString("vacced"), false, "vacuumed", null);
		},
		
		openOptions: function() {
			openDialog("chrome://cfxhelper/content/options.xul", "", "chrome,titlebar,toolbar,centerscreen,modal");
		},
		
		prompt: function() {
			let pmtService = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
			if(cfxc.observer.isPrefChanged() === true) {
				if(this.getPref("WarnOnRestart") === true) {
					if(pmtService.confirm(window, "Chromifox Extreme", "In order for the changes to take effect Firefox must restart.")) {
						this.restartApp();
					}
				} else {
					this.restartApp();
				}
			}
		},
		
		unLoad: function() {
			cfxc.observer.unRegister();
		},
	};

	cfxc.observer = {
		branch: null,
		prefChanged: null,
		
		register: function() {
			this.branch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).getBranch("extensions.cfxh.");
			this.branch.QueryInterface(Ci.nsIPrefBranch2);
			this.branch.addObserver("", this, false);
		},
		
		isPrefChanged: function() {
			return this.prefChanged;
		},
		
		observe: function(subject, topic, data) {
			if(topic != "nsPref:changed") {
				return;
			}
 
			switch(data) {
				case "DefaultTabs":
					this.prefChanged = true;
					break;
				case "DisableUI":
					this.prefChanged = true;
					break;
				case "Tabs":
					this.prefChanged = true;
					break;
				default:
					break;
			}
		},

		unRegister: function() {
			this.branch.removeObserver("", this);
		},
	};

window.addEventListener("load", function() { cfxc.h.onLoad(); }, false);
window.addEventListener("unload", function() { cfxc.h.unLoad(); }, false);
